package jwlee.testproxy;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
//测试用cglib做代理
public class CglibTester {
	public static void main(String rags[]) {
		testCglib();
	}

	private static void testCglib() {
		MethodInterceptor callback = new MethodInterceptor() {
			@Override
			public Object intercept(Object object, Method method,
					Object[] args, MethodProxy methodProxy) throws Throwable {
				System.out.println("----MethodInterceptor start...");
				Object result = methodProxy.invokeSuper(object, args);//
				System.out.println("----MethodInterceptor ending...");
				return result.toString().toUpperCase();
			}
		};
		Target proxyTarget = (Target) createProxy(Target.class, callback);
		
		String res = proxyTarget.execute();
		System.out.println(res);
	}

	/**
	 * 构造cglib代理类
	 * @param targetClass
	 * @param callback
	 * @return
	 */
	public static Object createProxy(Class<Target> targetClass, Callback callback) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(targetClass);
		enhancer.setCallback(callback);
		return enhancer.create();
	}
}

class Target {
	public String execute() {
		System.out.println("----Target.execute...");
		String message = "hello";
		System.out.println(message);
		return message;
	}
}
